import java.net.*;
import java.awt.image.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.io.*;
import org.w3c.tidy.Tidy;
import java.util.*;

public class WebRequest
{
    private String _host;
    private String _filename;

    public WebRequest()
    {
        _host = "";
        _filename = "";
    }

    public WebRequest(String url)
    {
        if (url.indexOf("www.") == -1)
        {
            url = unShorten(url);
        }
        _host = url.substring(url.indexOf("www."), url.indexOf("/", 7));
        _filename = url.substring(url.indexOf("/", 7)); 
    }

    public String fetchFavIcon() 
    {
        try
        {
            URL url = new URL("http://www.google.com/s2/favicons?domain=" + _host);
            URLConnection urlConnection = url.openConnection();

            BufferedInputStream in = new BufferedInputStream(urlConnection.getInputStream());

            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream( "favicon.bmp" ));

            int i;
            while ((i = in.read()) != -1) {
                out.write(i);
            }
            out.flush();

            out.close();
            in.close();

            this.convertFavIcon();

            return "Success!";
        }
        catch (Exception e)
        {
            System.out.println(e);
        }
        return "Failed...";
    }

    public String fetchPage()
    {

        //         String _host = "www.omnimaga.org";
        //         String _filename = "index.php?topic=7261.0;wap2";
        int _port = 80;

        try
        {
            Socket sk = new Socket(_host, _port);

            if (sk.isConnected())
            {
                PrintWriter out = new PrintWriter(sk.getOutputStream(),true);
                out.println("GET /" + _filename + " HTTP/1.0");
                out.println("Host: " + _host);
                out.println("");
                out.flush();

                BufferedReader in = new BufferedReader(new InputStreamReader(sk.getInputStream()));

                String response = "";
                String data = "";
                boolean more = true;
                while (more) 
                { 
                    //read one line at a time 
                    response = in.readLine(); 

                    //print the line if any 
                    if (response == null) 
                    {
                        more = false;
                    }
                    else
                    {
                        data += response + "\n";
                    }
                }           
                return data;
            }
        }
        catch (Exception e)
        {
            System.out.println("Error: " + e.getMessage());
        }

        return "Fetch Failed!";
    }

    public String fetchPage(String cmd)
    {

        //         String _host = "www.omnimaga.org";
        //         String _filename = "index.php?topic=7261.0;wap2";
        int _port = 80;

        try
        {
            Socket sk = new Socket(_host, _port);

            if (sk.isConnected())
            {
                PrintWriter out = new PrintWriter(sk.getOutputStream(),true);
                out.println("GET /" + _filename + " HTTP/1.0");
                out.println("Host: " + _host);
                out.println("");
                out.flush();

                BufferedReader in = new BufferedReader(new InputStreamReader(sk.getInputStream()));

                String response = "";
                String data = "";
                boolean more = true;
                while (more) 
                { 
                    //read one line at a time 
                    response = in.readLine(); 

                    //print the line if any 
                    if (response == null) 
                    {
                        more = false;
                    }
                    else
                    {
                        data += response + "\n";
                    }
                }           
                if(cmd.equals("stripheader"))
                {
                    data = data.substring(data.indexOf("<!DOCTYPE"));
                }
                return data;
            }
        }
        catch (Exception e)
        {
            System.out.println("Error: " + e.getMessage());
        }

        return "Fetch Failed!";
    }

    public void convertFavIcon()
    {
        try
        {
            //colored image path
            BufferedImage image = ImageIO.read(new  
                    File("C:\\APCS Course Files\\Module 05\\Mod05 Lesson\\adfgh\\favicon.bmp"));

            //getting width and height of image
            double image_width = image.getWidth();
            double image_height = image.getHeight();

            BufferedImage bimg = null;
            BufferedImage img = image;

            //drawing a new image       
            bimg = new BufferedImage((int)image_width, (int)image_height,
                BufferedImage.TYPE_INT_RGB);
            Graphics2D gg = bimg.createGraphics();
            gg.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);

            for(int x = 0; x < img.getWidth(null); x++)
            {
                for(int y = 0; y < img.getHeight(null); y++)
                {
                    int pixel = bimg.getRGB(x, y);
                    int red = (pixel >> 16) & 0xff;
                    int green = (pixel >> 8) & 0xff;
                    int blue = (pixel) & 0xff;
                    int color = red + blue + green;
                    if(color > 16 && color <= 384)
                    {
                        bimg.setRGB(x, y, Color.DARK_GRAY.getRGB());
                    }
                    if(color <= 16)
                    {
                        bimg.setRGB(x, y, Color.BLACK.getRGB());
                    }
                    if(color >= 749)
                    {
                        bimg.setRGB(x, y, Color.WHITE.getRGB());
                    }
                    if(color > 384 && color < 749)
                    {
                        bimg.setRGB(x, y, Color.LIGHT_GRAY.getRGB());
                    }
                }
            }
            //saving black and white image onto drive
            String temp = "favicon.bmp";
            File fi = new File("C:\\APCS Course Files\\Module 05\\Mod05 Lesson\\adfgh\\" + temp);
            ImageIO.write(bimg, "bmp", fi);
        }
        catch (Exception e)
        {
            System.out.println(e);
        }
    }

    public String unShorten(String u)
    {

        //         String _host = "www.omnimaga.org";
        //         String _filename = "index.php?topic=7261.0;wap2";
        int _port = 80;

        try
        {
            Socket sk = new Socket("api.unfwd4.me", _port);

            if (sk.isConnected())
            {
                PrintWriter out = new PrintWriter(sk.getOutputStream(),true);
                out.println("GET /?url=" + u + " HTTP/1.0");
                out.println("Host: api.unfwd4.me");
                out.println("");
                out.flush();

                BufferedReader in = new BufferedReader(new InputStreamReader(sk.getInputStream()));

                String response = "";
                String data = "";
                boolean more = true;
                while (more) 
                { 
                    //read one line at a time 
                    response = in.readLine(); 

                    //print the line if any 
                    if (response == null) 
                    {
                        more = false;
                    }
                    else if (response.indexOf("http://") == 0)
                    {
                        data = response;
                    }
                }           
                return data;
            }
        }
        catch (Exception e)
        {
            System.out.println("Error: " + e.getMessage());
        }

        return "Fetch Failed!";
    }

    public String fetchPageTidy()
    {
        try
        {
            DataOutputStream outFile = new DataOutputStream(new FileOutputStream("page.txt"));

            String data = this.fetchPage("stripheader");

            outFile.writeUTF(data);
            outFile.close();

            FileInputStream inFile   = new FileInputStream(new File("page.txt"));
            DataOutputStream outFile2 = new DataOutputStream(new FileOutputStream("tidy.txt"));

            Tidy tidy = new Tidy();
            tidy.setQuiet(true);
            tidy.setShowWarnings(false);
            tidy.setShowErrors(0);
            tidy.parse(inFile, outFile2); 
            outFile2.close();

            deleteFile("page.txt");
            
            return "Success!";
        }
        catch (Exception e)
        {
            System.out.println("Error: " + e.getMessage());
        }
        return "Failed...";
    }

    public void deleteFile(String name)
    {
        String fileName = name;
        // A File object to represent the filename
        File f = new File(fileName);

        // Make sure the file or directory exists and isn't write protected
        if (!f.exists())
            throw new IllegalArgumentException("Delete: no such file or directory: " + fileName);

        if (!f.canWrite())
            throw new IllegalArgumentException("Delete: write protected: " + fileName);

        // If it is a directory, make sure it is empty
        if (f.isDirectory())
        {
            String[] files = f.list();
            if (files.length > 0)
                throw new IllegalArgumentException("Delete: directory not empty: " + fileName);
        }

        // Attempt to delete it
        boolean success = f.delete();

        if (!success)
            throw new IllegalArgumentException("Delete: deletion failed");
    }

}